package com.qianfeng.smartmetting.config;

import com.alibaba.fastjson2.JSON;
import com.qianfeng.smartmetting.util.JwtUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


//用户认证成功的处理
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , Authentication authentication) throws IOException, ServletException {
        //向前端返回JSON数据
        //类型强转成UserDetails
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //生成token
        JwtUtil jwtUtil  = new JwtUtil();
        String token = "Bearer "+jwtUtil.generateToken(userDetails.getUsername());


        Map map = new HashMap();
        map.put("code",1);
        map.put("msg","登录成功");
        map.put("data",authentication.getPrincipal());
        map.put("token",token);


        String jsonString = JSON.toJSONString(map);
        //设置响应头信息
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setHeader("Authorization",token);

        //后端向前端发送数据,参数是字符串类型
        httpServletResponse.getWriter().write(jsonString);


    }

}
